package springboot.example.tools;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

@Component
public class RoundCalculationUtil {

    @Value("${round.calculation}")
    private String calculationWay;

    public BigDecimal reCalculateAmount(BigDecimal amount){
        if(calculationWay.equals("currencyround")){
            return currencyRound(amount);
        }else {
            return round(amount);
        }
    }

    public BigDecimal round(BigDecimal amount) {
        BigDecimal result = amount.setScale(0, BigDecimal.ROUND_DOWN);
        BigDecimal lastRound2 = amount.setScale(2, BigDecimal.ROUND_DOWN).subtract(result);
        if (lastRound2.compareTo(new BigDecimal("0.50")) >= 0) {
            result = result.add(new BigDecimal("1"));
        }

        return result;
    }

    public BigDecimal currencyRound(BigDecimal amount){
        BigDecimal result = amount.setScale(2,BigDecimal.ROUND_DOWN);
        BigDecimal firstRound4=amount.setScale(4,BigDecimal.ROUND_DOWN);
        BigDecimal lastRound2=firstRound4.subtract(firstRound4.setScale(2,BigDecimal.ROUND_DOWN));
        if(lastRound2.compareTo(new BigDecimal("0.0005"))>=0){
            result=result.add(new BigDecimal("0.01"));
        }
        return result;
    }
}
